<?php

class moduleAdmin {
	static function beforeAction() {
		header("Content-Type: text/html; charset=utf-8");
	}

	static function actionMain() {
		fpsView::render('admin', null, 'admin');
	}


	static function actionBooks() {

		$list = fpsDB::find(
			APP_TABLE_BOOKS, [],
			[],
			['sort'=>['_id'=>1]]
		);

		fpsView::render('books', compact('list'), 'admin');
	}


	static function actionAddBook() {

		$id = fps_post('id', 0, 'intval');

		$id = 1;
		$now = time();

		if (count($_FILES)) {
			$path = '/data/upload';
			$file_attachment_arr = [];
			foreach ($_FILES as $item){
				// var_dump($item);

				if ($item["error"] > 0) {
					json_out(404, $item["error"]);
				}else{
					$file_name = uniqid() . '_' . date('Ymdhis');
					$file_types = explode ( ".", $item['name']);
					$file_type = $file_types[count($file_types) - 1];
					$file_tmp_path = $path."/".$file_name.'.'.$file_type;
					$file_save_path = PROJECT_ROOT.$file_tmp_path;

					$file_attachment_arr[] = [
						'file_name' => $item['name'],
						'file_type' => $item['type'],
						'file_size' => round($item['size'] / 1024, 1),
						'file_unit' => 'kb',
						'file_extension' => $file_type,
						'file_tmp_name' => $file_name,
						'file_tmp_path' => $file_save_path,
						'file_preview_path' => $file_tmp_path
					];
					move_uploaded_file($item['tmp_name'], $file_save_path);
				}
			}
			$_POST['cover'] = array_merge(val($_POST, 'cover', []), $file_attachment_arr);
		}



		if ($id) {
			// 编辑记录
			$cond = [
				'_id' => $id
			];

			$old_data = fpsDB::findOne(APP_TABLE_BOOKS, $cond);
			if (!$old_data) {
				json_out(404, '记录没有找到或已经被删除');
			}

			$postData = $_POST;

			$data = array_merge(self::preSaveBookData($postData), [
				'_id' => $old_data['_id'],
				'updateTime' => $now
			]);
		}else{
			// 新建记录
			$_id = fpsDB::index(APP_TABLE_BOOKS);
			// 检查是否重复
			$old_data = fpsDB::findOne(APP_TABLE_BOOKS, ['_id' => $_id]);

			if ($old_data) {
				json_out(404, 'id已存在：'.$_id);
			}

			$postData = $_POST;

			$data = array_merge(self::preSaveBookData($postData), [
				'_id' => $_id,
				'createTime' => $now,
				'updateTime' => $now
			]);
		}

		fpsDB::save(APP_TABLE_BOOKS, $data);


		json_out(0, $_POST);
	}

	// 处理保存数据
	static function preSaveBookData($postData){

		if ($postData) {
			$data = [
				'title' => $postData['title'],
				'author' => $postData['author'],
				'desc' => $postData['desc'],

				'cover' => val($postData, 'cover', []),

				'isDeleted' => val($postData, 'isDeleted', false)
			];

			return $data;
		}else{
			return [];
		}
	}

}